//
//  ZYCPublishCircleFriendsView.m
//  ZDSC
//
//  Created by ZDTX on 2021/9/19.
//

#import "ZYCPublishCircleFriendsView.h"
#import "LxGridViewFlowLayout.h"
#import "TZTestCell.h"
#import "ZYCPublishCircleFriendsFooterView.h"

#define maxContent 500
#define BTImageTotalNumber 9
#define ZYCContentPlaceholder @"请输入内容..."
#define ZYCContentPlaceholderColor [UIColor colorWithHexString:@"#BBBBBB" alpha:1.0]

@interface ZYCPublishCircleFriendsView ()<UICollectionViewDelegate,UICollectionViewDataSource,UITextViewDelegate>


@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *comfirmButton;
@property (nonatomic, strong) UITextView *contentTextView;
@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) LxGridViewFlowLayout * layout;
@property (nonatomic, strong) UIView *line;


@end
@implementation ZYCPublishCircleFriendsView

- (void)reload{
    [self.collectionView reloadData];
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.cancelButton];
        [self addSubview:self.comfirmButton];
        [self addSubview:self.contentTextView];
        [self addSubview:self.collectionView];
        [self addSubview:self.comfirmButton];
        [self addSubview:self.line];
        
        [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(18.0f);
            make.top.equalTo(self).offset(42.0f);
            make.size.mas_equalTo(CGSizeMake(58.0f, 33.0f));
        }];
        
        [self.comfirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.self).offset(-18.0f);
            make.top.equalTo(self.self).offset(42.0f);
            make.size.mas_equalTo(CGSizeMake(58.0f, 33.0f));
        }];

        [self.contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.cancelButton.mas_bottom).offset(66.0f);
            make.left.equalTo(self).offset(18.0f);
            make.right.equalTo(self).offset(-18.0f);
            make.height.mas_equalTo(103.f);
        }];
        
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentTextView.mas_bottom).offset(10.0f);
            make.left.equalTo(self).offset(33.0f);
            make.right.equalTo(self).offset(-33.0f);
            make.bottom.equalTo(self);
        }];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}



//时时监听
- (void)textChanged:(NSNotification*)noti{
    //限制输入字数
    [self textViewMaxTextCount:self.contentTextView AndMaxCount:maxContent];
}

/// UITextView字数限制
/// @param textView textView
/// @param maxCount 限制字数
- (void)textViewMaxTextCount:(UITextView *)textView AndMaxCount:(int)maxCount{
    NSString *toBeString =textView.text;
    NSString *lang = [[UIApplication sharedApplication] textInputMode].primaryLanguage;
    if ([lang isEqualToString:@"zh-Hans"]) { // 中文输入
        UITextRange *selectedRange = [textView markedTextRange];
        // 获取高亮部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        if (!position) {// 没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (toBeString.length > maxCount) {
                textView.text = [toBeString substringToIndex:maxCount];
                [MrjToast makeToast:@"字数不能超过500字" makeView:[UIApplication sharedApplication].keyWindow];
            }
        }else{//有高亮选择的字符串，则暂不对文字进行统计和限制
            
        }
    }else{//中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > maxCount) {
            textView.text = [toBeString substringToIndex:maxCount];
            [MrjToast makeToast:@"字数不能超过500字" makeView:[UIApplication sharedApplication].keyWindow];
        }
    }
}

#pragma mark UICollectionViewDelegate && UICollectionViewDataSource
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.selectedPhotos.count == BTImageTotalNumber) {
        return self.selectedPhotos.count;
    }else{
        return self.selectedPhotos.count + 1;
    }
}

-(__kindof UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([TZTestCell class]) forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    cell.gifLable.hidden = YES;
    
    if (indexPath.item == self.selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"x"];
        cell.deleteBtn.hidden = YES;
    }else {
        cell.imageView.image = self.selectedPhotos[indexPath.row];
        cell.asset = self.selectedAssets[indexPath.item];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

-(void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == self.selectedPhotos.count) {
        if ([self.delegate respondsToSelector:@selector(publishCircleFriendsViewDidAddPhoto)]) {
            [self.delegate publishCircleFriendsViewDidAddPhoto];
        }
    }else{
        [self browserPhotoIndexPath:indexPath];
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    ZYCPublishCircleFriendsFooterView *footer = nil;
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([ZYCPublishCircleFriendsFooterView class]) forIndexPath:indexPath];
    }
    return footer;
}

- (void)browserPhotoIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray *browserDataArr = [NSMutableArray array];
    NSUInteger index = indexPath.item;
    [self.selectedAssets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YBIBImageData *data = [YBIBImageData new];
        data.imagePHAsset = obj;
        [browserDataArr addObject:data];
    }];
    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSourceArray = browserDataArr;
    browser.currentPage = index;
    [browser show];
}

#pragma mark - action
- (void)clickCancelAction:(UIButton *)sender{
    if ([self.delegate respondsToSelector:@selector(publishCircleFriendsViewDidCancel)]) {
        [self.delegate publishCircleFriendsViewDidCancel];
    }
}

- (void)clickComfirmAction:(UIButton *)sender{
    if ([self.delegate respondsToSelector:@selector(publishCircleFriendsViewDidComfirm)]) {
        [self.delegate publishCircleFriendsViewDidComfirm];
    }
}

-(void) deleteBtnClick:(UIButton *)sender{
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    [self.collectionView reloadData];
}

#pragma mark - setters
-(void) setSelectedPhotos:(NSMutableArray *)selectedPhotos{
    _selectedPhotos = selectedPhotos;
    [self.collectionView reloadData];
}

#pragma mark - getters

- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithTitle:@"取消" normalTitleColor:HEX_RGB(@"000000") selectTitleColor:HEX_RGB(@"000000") titleFont:kCustomFont(@"PingFangSC-Regular", 16.0f)];
        [_cancelButton addTarget:self action:@selector(clickCancelAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (UIButton *)comfirmButton {
    if (!_comfirmButton) {
        _comfirmButton = [[UIButton alloc] init];
        [_comfirmButton setTitle:@"发布" forState:UIControlStateNormal];
        _comfirmButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 16.0f);
        [_comfirmButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _comfirmButton.backgroundColor = HEX_RGB(@"#009B4C");
        [_comfirmButton addTarget:self action:@selector(clickComfirmAction:) forControlEvents:UIControlEventTouchUpInside];
        _comfirmButton.layer.cornerRadius = 2.0f;
        _comfirmButton.layer.masksToBounds = YES;
    }
    return _comfirmButton;
}


- (NSString *)content{
    if ([self.contentTextView.text isEqualToString:ZYCContentPlaceholder]) {
        return nil;
    }
    return self.contentTextView.text;
}

- (UITextView *)contentTextView {
    if (!_contentTextView) {
        _contentTextView = [[UITextView alloc] init];
        _contentTextView.delegate = self;
        _contentTextView.font = kCustomFont(@"PingFangSC-Regular", 16.0f);
        _contentTextView.text = ZYCContentPlaceholder;
        _contentTextView.textColor = ZYCContentPlaceholderColor;
    }
    return _contentTextView;
}

-(UICollectionView *) collectionView
{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.contentInset = UIEdgeInsetsMake(10, 0, 10, 0);
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.scrollEnabled = NO;
        _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:NSStringFromClass([TZTestCell class])];
        [_collectionView registerClass:[ZYCPublishCircleFriendsFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([ZYCPublishCircleFriendsFooterView class])];
    }
    return _collectionView;
}

-(LxGridViewFlowLayout *) layout{
    if (!_layout) {
        _layout = [[LxGridViewFlowLayout alloc] init];
        _layout.itemSize = CGSizeMake(98.0, 98.0f);
        _layout.minimumLineSpacing = 10;//行间距
        _layout.minimumInteritemSpacing = 10;//列间距
        _layout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 10);
        _layout.footerReferenceSize = CGSizeMake(kScreenWidth, 16.0f);
    }
    return _layout;
}

#pragma mark - LxGridViewDataSource

/// 以下三个方法为长按排序相关代码
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < _selectedPhotos.count;
}

- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < _selectedPhotos.count && destinationIndexPath.item < _selectedPhotos.count);
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    [_selectedPhotos removeObjectAtIndex:sourceIndexPath.item];
    [_selectedPhotos insertObject:image atIndex:destinationIndexPath.item];
    
    id asset = _selectedAssets[sourceIndexPath.item];
    [_selectedAssets removeObjectAtIndex:sourceIndexPath.item];
    [_selectedAssets insertObject:asset atIndex:destinationIndexPath.item];
    
    [_collectionView reloadData];
}




#pragma mark - UITextViewDelegate
-(void) textViewDidEndEditing:(UITextView *)textView{
    if (textView.text.length < 1) {
        textView.text = ZYCContentPlaceholder;
        textView.textColor = ZYCContentPlaceholderColor;
    }
}

-(void) textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:ZYCContentPlaceholder]) {
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
}




- (void)textViewDidChange:(UITextView *)textView{
    static CGFloat maxHeight = 60.0f;
    CGRect frame = textView.frame;
    CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
    CGSize size = [textView sizeThatFits:constraintSize];
    if (size.height <= frame.size.height) {
        size.height=frame.size.height;
    }else if(size.height >= maxHeight){
        size.height = maxHeight;
        textView.scrollEnabled = YES;  // 允许滚动
    }else{
        textView.scrollEnabled = NO;    // 不允许滚动
    }
    textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
}
@end
